from django.contrib.auth.backends import ModelBackend
import re
from .models import User

def jwt_response_payload_handler(token, user=None, request=None):
    """重寫JWT登陸視圖的構造響應數據函數,多追加 user_id 和 username"""
    print('xxx')
    return {
        'token':token,
        'user_id':user.id,
        'username':user.username
    }

def get_user_by_account(account):
    """
    通過傳入的賬號動態獲取user 模型對象
    :param account: 有可能是手機號,有可能是用戶名
    :return: user或None
    """
    try:
        if re.match(r'1[3-9]\d{9}$',account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username = account)
    except User.DoesNotExist:
        return None #　如果沒有查到返回None
    else:
        return user # 注意不要攜程模型類

class UsernameMobileAuthBackend(ModelBackend):
    """修改django的認證類,爲了實現多賬號登陸"""
    def authenticate(self, request, username=None, password=None, **kwargs):

        # 獲取到user
        user = get_user_by_account(username)

        # 判斷當前前端傳入的密碼是否正確
        if user and user.check_password(password):
        # 返回user
            return user